package com.yongqi.duocai.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yongqi.duocai.entity.Goods;
import com.yongqi.duocai.entity.Order;
import com.yongqi.duocai.entity.OrderInfo;
import com.yongqi.duocai.entity.ShoppingCart;
import com.yongqi.duocai.entity.param.OrderParam;
import com.yongqi.duocai.entity.param.ShoppingCartParam;
import com.yongqi.duocai.entity.result.ChooseShoppingInfoResult;
import com.yongqi.duocai.entity.result.ShoppingCarResult;
import com.yongqi.duocai.entity.vo.PromptlyGoodVo;
import com.yongqi.duocai.entity.vo.ShoppingGoodsVo;
import com.yongqi.duocai.exception.BusinessException;
import com.yongqi.duocai.exception.ResponseEnum;
import com.yongqi.duocai.service.GoodsService;
import com.yongqi.duocai.service.OrderInfoService;
import com.yongqi.duocai.service.OrderService;
import com.yongqi.duocai.service.ShoppingCartService;
import com.yongqi.duocai.utils.JsonResult;
import com.yongqi.duocai.utils.OrderNumUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 夏亮辉
 * @since 2021-06-19
 */
@RestController
@Api(tags = "ShoppingCartController")
@RequestMapping("/shoppingCar")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private GoodsService goodsService;

    // 记录立即购买商品在购物车的id;
    private List<Integer> shoppIds;

    @GetMapping("/query")
    @ApiOperation(value = "根据用户id查询其购物车信息")
    public JsonResult queryGoodsByUserId(Integer userId){
        JsonResult jsonResult = new JsonResult();
        List<ShoppingCarResult> list = shoppingCartService.queryInfo(userId);
        if(list.size() > 0){
            jsonResult.setCode(200);
            jsonResult.setData(list);
        }else if(list.size() == 0){
            jsonResult.setCode(200);
            jsonResult.setMessage("很遗憾！您的购物车空空如也！！");
        }
        return jsonResult;
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加购物车信息")
    public JsonResult add(ShoppingCartParam param){
        JsonResult jsonResult = new JsonResult();

        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(param, shoppingCart);
        BigDecimal count = new BigDecimal(Integer.toString(param.getCount()));
        BigDecimal price = param.getPrice();
        BigDecimal sum = count.multiply(price);
        shoppingCart.setSumPrice(sum);
        boolean res = false;
        // 对购物车商品进行查重
        // 根据用户id查询其购物车信息
        List<ShoppingCarResult> shoppingCarResults = shoppingCartService.queryInfo(param.getUserId());
        for (ShoppingCarResult c : shoppingCarResults){
            if(c.getGoodsId().equals(param.getGoodsId())){
                // 设置购物车信息id
                shoppingCart.setId(c.getId());
                // 增加商品数量
                shoppingCart.setCount(c.getCount() + param.getCount());
                // 增加商品金额
                shoppingCart.setSumPrice(c.getSumPrice().add(sum));
                res = shoppingCartService.updateById(shoppingCart);
                if(res){
                    jsonResult.setCode(200);
                    jsonResult.setMessage("添加成功");
                    return jsonResult;
                }
            }
        }

        System.out.println(shoppingCart);

        res = shoppingCartService.save(shoppingCart);
        if (res) {
            jsonResult.setCode(200);
            jsonResult.setMessage("添加成功！");
        }
        return jsonResult;
    }

    @PutMapping("/update")
    @ApiOperation(value = "修改购物车商品数量")
    public JsonResult update(Integer id, Integer count, BigDecimal price){
        JsonResult jsonResult = new JsonResult();
        ShoppingCart shoppingCart = new ShoppingCart();
        BigDecimal count1 = new BigDecimal(Integer.toString(count));
        BigDecimal sum = count1.multiply(price);
        shoppingCart.setId(id);
        shoppingCart.setCount(count);
        shoppingCart.setSumPrice(sum);
        boolean res = shoppingCartService.updateById(shoppingCart);
        if(res){
            jsonResult.setCode(200);
            jsonResult.setMessage("修改成功！");
        }else {

        }
        return jsonResult;
    }

    @DeleteMapping("/del")
    @ApiOperation(value = "根据id批量删除购物车信息")
    public JsonResult delete(Integer[] ids){
        JsonResult jsonResult = new JsonResult();
        boolean res = shoppingCartService.removeByIds(Arrays.asList(ids));
        if(res){
            jsonResult.setCode(200);
            jsonResult.setMessage("删除成功！！");
        }else {
            jsonResult.setMessage("删除失败！");
        }
        return jsonResult;
    }

    @PostMapping("/get/order")
    @ApiOperation(value = "生成结算商品信息")
    public JsonResult getOrder(Integer[] ids, Integer userId){
        JsonResult jsonResult = new JsonResult();
        // 组装对象
        OrderInfo createInfo = new OrderInfo();
        boolean save = false;
        // 查询用户选中的购物车信息
        List<ShoppingCart> carts = shoppingCartService.listByIds(Arrays.asList(ids));

        if(carts.get(0).getUserId().equals(userId)){
            for (ShoppingCart c : carts){
                BeanUtils.copyProperties(c, createInfo);
                createInfo.setSumMoney(c.getSumPrice());
                createInfo.setUserId(userId);
                // 对组装的信息进行查重
                QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id", createInfo.getUserId())
                        .eq("goods_id", createInfo.getGoodsId())
                        .eq("count", createInfo.getCount())
                        .eq("sum_money", createInfo.getSumMoney());
                OrderInfo one = orderInfoService.getOne(queryWrapper);
                if(one != null){
                    throw new BusinessException(ResponseEnum.ORDERINF_CREATE_ERROR);
                }

                // 保存入数据库
                save = orderInfoService.save(createInfo);
            }
            if(save){
                jsonResult.setCode(200);
                jsonResult.setMessage("添加成功！！");
            }else {
                jsonResult.setMessage("添加失败");
            }
        }else {
            throw new BusinessException(ResponseEnum.USER_INVALID_ERROR);
        }

        return jsonResult;
    }

    @PostMapping("/set/order")
    @ApiOperation(value = "提交购物车商品信息表单")
    public JsonResult setOrder(Integer[] ids, OrderParam param){
        JsonResult jsonResult = new JsonResult();
        boolean res = false;

        OrderInfo orderInfo = new OrderInfo();
        Order order = new Order();
        // 查询用户选中的购物车商品信息
        List<ShoppingCart> shoppingInfos = shoppingCartService.listByIds(Arrays.asList(ids));
        Integer sumCount = 0;
        BigDecimal total = new BigDecimal(0.0);
        String orderNo = null;
        // 计算订单商品数量和总价格
        for(ShoppingCart c : shoppingInfos){
            sumCount += c.getCount();
            total = total.add(c.getSumPrice());
        }

        // 组装订单商品信息对象
        for (ShoppingCart c : shoppingInfos){
            BeanUtils.copyProperties(c, orderInfo);
            orderInfo.setSumMoney(c.getSumPrice());
            res = orderInfoService.save(orderInfo);
            // 保存信息
            if(res){
                BeanUtils.copyProperties(param, order);
                // 商品信息详情
                order.setSellInfoId(orderInfo.getId());
                // 订单编号
                orderNo = OrderNumUtils.createNum(c.getUserId());
                order.setNo(orderNo);
                order.setSumCount(sumCount);
                order.setState(1);
                order.setMakeOutState(false);
                order.setTotal(total);
                // 保存信息
                res = orderService.save(order);
                if(res){
                    // 删除购物车信息
                    res = shoppingCartService.removeById(c.getId());
                }
            }
        }

        if(res){
            jsonResult.setCode(200);
            jsonResult.setData(orderNo);
            jsonResult.setMessage("创建成功！");
        }else {
            jsonResult.setMessage("创建失败");
        }

        return jsonResult;
    }

    @GetMapping("/goods/info")
    @ApiOperation("根据用户id查询购物车订单商品详情")
    public JsonResult query(Integer userId, Integer[] ids){
        JsonResult jsonResult = new JsonResult();
        List<ChooseShoppingInfoResult> shoppingInfos = shoppingCartService.queryGoods(userId, ids);
        if(shoppingInfos.size() <= 0){
            jsonResult.setMessage("参数错误");
            return jsonResult;
        }
        ShoppingGoodsVo vo = new ShoppingGoodsVo();
        BigDecimal sum = new BigDecimal(0);
        for (ChooseShoppingInfoResult s: shoppingInfos){
            sum = s.getSumPrice().add(sum);
        }
        vo.setShoppingInfoList(shoppingInfos);
        vo.setTotalMoney(sum);
        if(vo != null){
            jsonResult.setCode(200);
            jsonResult.setData(vo);
        }
        return jsonResult;
    }


    @PostMapping("/promptly/shopping")
    @ApiOperation("立即购买提交表单")
    public JsonResult promptly(Integer ids, Integer count, OrderParam param){
        JsonResult jsonResult = new JsonResult();
        boolean res = false;
        Goods goods = goodsService.getById(ids);
        OrderInfo info = new OrderInfo();
        info.setUserId(param.getUserId());
        info.setGoodsId(ids);
        info.setCount(count);
        info.setSumMoney(goods.getSellingPrice().multiply(new BigDecimal(count)));
        res = orderInfoService.save(info);
        Order order = new Order();
        if(res){
            BeanUtils.copyProperties(param, order);
            order.setSellInfoId(info.getId());
            order.setNo(OrderNumUtils.createNum(param.getUserId()));
            order.setSumCount(count);
            order.setTotal(info.getSumMoney());
            order.setState(1);
            order.setMakeOutState(false);
            res = orderService.save(order);
        }
        if (res){
            jsonResult.setCode(200);
            jsonResult.setData(order.getNo());
            jsonResult.setMessage("创建成功！");
        }
        return jsonResult;
    }

    @GetMapping("/promptly/shopping/info")
    @ApiOperation("查询立即购买商品信息详情")
    public JsonResult promptlyGoodsInfo(Integer id, Integer count){
        JsonResult jsonResult = new JsonResult();
        Goods goods = goodsService.getById(id);
        PromptlyGoodVo vo = new PromptlyGoodVo();
        BeanUtils.copyProperties(goods, vo);
        vo.setCount(count);
        vo.setTotalMoney(goods.getSellingPrice().multiply(new BigDecimal(count)));
        jsonResult.setCode(200);
        jsonResult.setData(vo);

        return jsonResult;
    }

}

